package api

import (
	"log"

	"gitee.com/dingiyan/goMyAdmin/db"
	"gitee.com/dingiyan/goMyAdmin/service/dialect"
	"gitee.com/dingiyan/goMyAdmin/service/interfaces"
	"github.com/gin-gonic/gin"
)

// 响应成功结果
func success(data any) gin.H {
	return gin.H{"code": 0, "msg": "success", "data": data}
}

// 响应失败结果
func resError(code int, msg string) any {
	return gin.H{"code": code, "msg": msg, "data": nil}
}

// 工具，将server对象转为datasourcesConfig对象
//
// 第二个参数可替换一个ds对象的Database字段来连接到不同database
func serverToDatasourcesConfig(server *db.Server, args ...any) interfaces.DatasourcesConfig {
	if len(args) > 0 {
		dbName := args[0].(string)
		if dbName != "" {
			server.Database = dbName
		}
	}
	return interfaces.DatasourcesConfig{
		Host:     server.IP,
		Port:     server.Port,
		Database: server.Database,
		User:     server.User,
		Password: server.Password,
	}
}

func getUserId(c *gin.Context) uint {
	userId, isExist := c.Get("userId")
	if !isExist {
		log.Println("ctx没有找到userId")
		return 0
	}
	userId1, ok := userId.(uint)
	if !ok {
		log.Println("ctx assert uint userId 出错")
		return 0
	}

	return userId1
}

func getUserName(c *gin.Context) string {
	userName, isExist := c.Get("userName")
	if !isExist {
		return ""
	}
	userName1, ok := userName.(string)
	if !ok {
		return ""
	}
	return userName1
}

// 获取数据库管理对象
func getDBManager(userId uint, dsId uint, databaseName string) (interfaces.DBManager, error) {
	dsRecord, err := db.GetUsersServerById(userId, dsId)
	if err != nil {
		return nil, err
	}

	config := serverToDatasourcesConfig(dsRecord, databaseName)
	dbm := dialect.GetDialect(dialect.DialectMysql)
	_, err1 := dbm.ConnectDatasources(&config)
	if err1 != nil {
		return nil, err1
	}

	return dbm, nil
}
